<template>
  <el-header class="header">
    <el-header class="header_he">
      <div>
        <img src="@/assets/images/systemManagement/菜单.png" alt="" />
        <span>权限管理</span>
      </div>
      <div>
        <img :src="imgUrl" alt="" />
        <span>{{ userName }}</span>
      </div>
    </el-header>
  </el-header>

  <!-- 操作栏 -->
  <div class="operation-buttons">
    <el-button type="primary" @click="handleAdd">+ 添加</el-button>
    <el-button @click="handleRefresh" type="info"><el-icon><Refresh /></el-icon>刷新</el-button>
  </div>

  <!-- 权限表格 -->
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="name" label="名称" width="120" />
    <el-table-column prop="menuNames" label="权限" />
    <el-table-column prop="status" label="状态" width="80">
      <template #default="scope">
        <span :class="scope.row.status === '启用' ? 'status-active' : 'status-disabled'">
          {{ scope.row.status }}
        </span>
      </template>
    </el-table-column>
    <el-table-column prop="description" label="备注" />
    <el-table-column label="操作" width="80">
      <template #default="scope">
        <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
    background
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[8, 12, 15]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    class="pagination"
  />

  <!-- 新增/编辑模态框-->
  <el-dialog 
    v-model="dialogVisible" 
    :title="isEdit ? '编辑权限' : '新增权限'"  
    width="600px"
    :before-close="handleDialogClose"
  >
    <el-form 
      ref="formRef"  
      :model="form"  
      :rules="rules" 
      label-width="80px"
      class="dialog-form"
    >
      <!-- 名称 -->
      <el-form-item label="名称" prop="name">
        <el-input 
          placeholder="请输入名称" 
          v-model="form.name" 
          clearable 
          style="width: 100%"
        />
      </el-form-item>
      <!-- 权限-->
      <el-form-item label="权限" prop="permission">
        <el-cascader
          placeholder="请选择权限"
          v-model="form.permission"
          :options="permissionOptions"
          :props="{ 
            value: 'id', // 用原始数据的 id 作为 value
            label: 'title', // 用原始数据的 title 作为 label
            children: 'childList', // 用原始数据的 childList 作为 children
            multiple: true
          }"
          filterable
          style="width: 100%"
        />
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio value="启用">启用</el-radio>
          <el-radio value="禁用">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="form.remark" 
          type="textarea" 
          placeholder="请输入备注" 
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import yonghuImgUrl from '@/assets/images/systemManagement/菜单.png';
// import getPermissionMange from '@/components/api/PermissionMange'
import { getRoleList,getMenuList,getAddRole,getUpdateRole } from '@/components/api/PermissionMange'; 
// 基础状态
const imgUrl = ref(yonghuImgUrl);
const userName = ref("138****1234");
const dialogVisible = ref(false);
const formRef = ref(null);
const isEdit = ref(false);
const editId = ref('');
const saveLoading = ref(false);

// 分页配置
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(10); // 总条数
// 层级权限列表
let token = sessionStorage.getItem("token")
onMounted(() => {
    getMenuListFun()
})
let getMenuListFun = () => {
    getMenuList({token:token})
    .then(res => {
        if(res.code == 200){
            // console.log(res.dataset);  
            permissionOptions.value = bubbleSort(res.dataset) 
        }
    })
}
function bubbleSort(arr) {
  const newArr = [...arr];
  for (let i = 0; i < newArr.length - 1; i++) {
    if(newArr[i].childList.length>0){
      bubbleSort(newArr[i].childList);
    }
    for (let j = 0; j < newArr.length - 1 - i; j++) {
      if (newArr[j].orders < newArr[j + 1].orders) {
        [newArr[j], newArr[j + 1]] = [newArr[j + 1], newArr[j]];
      }
    }
  }
  return newArr;
}
const permissionOptions = ref([]);

const tableData = ref([]);
const getFailurelistall = ()=>{
  const aaa = {
    pageIndex:currentPage.value,
    pageSize:pageSize.value
  }
  getRoleList(aaa)
  .then(res=>{
        if (res.code === 200) {
          // console.log(res);
          total.value = res.dataset.totalSize
          tableData.value = res.dataset.roleList

          // tableData.name = res.dataset.name;
        }
  })
} 
getFailurelistall()
// 表单数据（与模态框双向绑定）
const form = reactive({
  name: '',          // 名称
  permission: [],    // 权限
  status: '启用',    // 状态
  remark: ''         // 备注
});

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  permission: [
    { required: true, message: '请选择权限', trigger: 'blur' }
  ]
});

// 表格数据源


// 打开新增模态框
const handleAdd = () => {
  resetForm();
  isEdit.value = false;
  dialogVisible.value = true;
  form.name = '';
  form.permission = [];
  form.status = 0;
  form.remark = '';
};
  let arrs = []
// 打开编辑模态框
const handleEdit = (row) => {
  isEdit.value = true;
  editId.value = row.id;
  form.name = row.name;
  let menusum = row.menuNames.split(',')
  // console.log(menusum)
  arrs = []
  ade(permissionOptions.value,menusum)
  // console.log(permissionOptions.value);
  form.permission = arrs;
  // console.log(form.permission);  
  form.status = row.status;
  form.remark = row.description;
  dialogVisible.value = true;
};
function ade(a,b){
  for(let i=0;i<a.length;i++){
    for(let j=0;j<b.length;j++){
      if(a[i].title==b[j]){
          arrs.push(a[i].id)
          if(a[i].childList){
            ade(a[i].childList,b)
          }
      }
    }
  }
}

let  data =null
const flattenAndUnique = arr => [...new Set(arr.flat(Infinity))];
// 保存表单
const handleSave = async () => {
  const formInstance = formRef.value;
  if (!formInstance) return;
  // 表单验证
  const valid = await formInstance.validate().catch(() => false);
  if (!valid) return;
  data = null
  saveLoading.value = true;
  try {
    if (isEdit.value) {
      // 编辑逻辑：更新表格数据
        const targetRow = editId.value;
        console.log(form.value,targetRow);
        data = {
          name: form.name,
          menuIds: flattenAndUnique(form.permission),
          status: form.status=="启用"? 1 :0,
          description: form.remark,
          id:targetRow
        };
        getUpdateRole(data)
        .then(res=>{
          if(res.code==200){
            ElMessage.success(isEdit.value ? '编辑成功' : '新增成功');
            dialogVisible.value = false;
            getFailurelistall()
          }
        })
    } else {
       data = {
        name: form.name,
        menuIds: flattenAndUnique(form.permission),
        status: form.status=="启用"? 1 :0,
        description: form.remark
      };
      getAddRole(data)
      .then(res=>{
        if(res.code==200){
          ElMessage.success(isEdit.value ? '编辑成功' : '新增成功');
          dialogVisible.value = false;
          getFailurelistall()
        }
      })
    } 
  } catch (error) {
    ElMessage.error(`操作失败：${error.message || '未知错误'}`);
  } finally {
    saveLoading.value = false;
    resetForm();
  }
};

// 重置表单
const resetForm = () => {
  form.name = '';
  form.permission = [];
  form.status = '启用';
  form.remark = '';
  formRef.value?.resetFields();
};

// 关闭模态框
const handleDialogClose = () => {
  ElMessageBox.confirm('确认关闭？未保存内容将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    resetForm();
    dialogVisible.value = false;
  }).catch(() => {});
};

// 分页逻辑
const handleSizeChange = (val) => { pageSize.value = val;getFailurelistall() };
const handleCurrentChange = (val) => { currentPage.value = val;getFailurelistall() };

// 刷新表格
const handleRefresh = () => {
  ElMessage.info('表格已刷新');
  // 实际场景：调用接口更新tableData
};
</script>

<style lang="less" scoped>
/* 头部样式 */
.header {
  background: #fff;
  height: 80px;
  border-bottom: 1px solid #ccc;
  box-shadow: 0 1px 2px #ccc;

  .header_he {
    height: 60%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    border-bottom: 1px solid #ccc;

    img { width: 20px; height: 20px; }
    span { padding: 0 10px; }
    div { display: flex; align-items: center; }
  }
}

/* 操作栏 */
.operation-buttons {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 50px;
}

/* 表格状态颜色 */
.status-active { color: #10b981; font-weight: 500; }
.status-disabled { color: #ef4444; font-weight: 500; }

/* 分页样式 */
.pagination {
  margin-top: 16px;
  text-align: right;
  padding: 12px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  flex-direction: row-reverse;
}

/* 模态框样式 */
.dialog-form {
  padding: 20px;

  .el-cascader {
    width: 100%; // 权限选择框自适应宽度
  }
}

.dialog-footer {
  text-align: right;
  gap: 10px;
}
</style>